package com.wushi.lenovo.asia5b.wxapi;

import android.app.Activity;

import com.mvp.utils.AppUtil;
import com.mvp.utils.ResString;
import com.mvp.utils.ToastUtil;
import com.tencent.mm.opensdk.modelmsg.SendAuth;
import com.tencent.mm.opensdk.modelmsg.SendMessageToWX;
import com.tencent.mm.opensdk.modelmsg.WXMediaMessage;
import com.tencent.mm.opensdk.modelmsg.WXWebpageObject;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.wushi.lenovo.asia5b.R;
import com.wushi.lenovo.asia5b.app_model.other.ShareBean;

/**
 * Created by zhangyuncai on 2020/6/22.
 */
public class WXUtils {
    private final static String APP_ID = "wxeb9cbbdcf7846c37";

    public void login(Activity activity) {
        if (wxAppInstalled(activity)) {
            regToWx(activity);

            // send oauth request
            final SendAuth.Req req = new SendAuth.Req();
            req.scope = "snsapi_userinfo";
            req.state = "none";
            api.sendReq(req);
        } else {
            ToastUtil.showToast(ResString.get(R.string.not_app));
        }
    }

    public void share(Activity activity, ShareBean shareBean) {
        if (!wxAppInstalled(activity)) {
            ToastUtil.showToast(ResString.get(R.string.not_app));
            return;
        }
        regToWx(activity);
        // 初始化一个WXWebpageObject对象
        WXWebpageObject webpageObject = new WXWebpageObject();
        // 填写网页的url
        webpageObject.webpageUrl = shareBean.getShareUrl();

        // 用WXWebpageObject对象初始化一个WXMediaMessage对象
        WXMediaMessage msg = new WXMediaMessage(webpageObject);
        // 填写网页标题、描述、位图
        msg.title = shareBean.getTitle();
        msg.description = shareBean.getDesc();
        // 如果没有位图，可以传null，会显示默认的图片
        msg.setThumbImage(shareBean.getBitmap());

        // 构造一个Req
        SendMessageToWX.Req req = new SendMessageToWX.Req();
        // transaction用于唯一标识一个请求（可自定义）
        req.transaction = "webpage";
        // 上文的WXMediaMessage对象
        req.message = msg;
        // SendMessageToWX.Req.WXSceneSession是分享到好友会话
        // SendMessageToWX.Req.WXSceneTimeline是分享到朋友圈
        req.scene = SendMessageToWX.Req.WXSceneSession;

        // 向微信发送请求
        api.sendReq(req);
    }

    private boolean wxAppInstalled(Activity activity) {
        return AppUtil.INSTANCE.isAppInstall(activity, "com.tencent.mm");
    }


    // IWXAPI 是第三方app和微信通信的openApi接口
    private IWXAPI api;

    private void regToWx(Activity activity) {
        // 通过WXAPIFactory工厂，获取IWXAPI的实例
        api = WXAPIFactory.createWXAPI(activity, APP_ID, true);

        // 将应用的appId注册到微信
        api.registerApp(APP_ID);


    }
}
